package com.apes.scm.income.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.Name;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.*;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.model.DutyCenter;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.party.service.PartyRoleService;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fico.finance.model.gl
 * @ClassName: MoneyIncome
 * @Author: pyb
 * @CreateTime: 2020-03-09 11:11
 * @Description: 资金收入单
 * @Version: 1.0
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = MoneyIncome.CONST_TABLE_NAME)
public class MoneyIncome extends Model {
    public final static String CONST_TABLE_NAME = "money_income";

    @Id
    @Column(name = "id", nullable = false, length = 120)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "资金收入单", padding = 8)
    @Comment("资金收入单号")
    private String id;

    @NotNull
    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.DATE)
    @Column(name = "post_date")
    @Comment("收入日期")
    private Date postDate;

    @Column(name = "source", length = 16)
    @Comment("来源单号")
    private String source;

    @Column(name = "source_business_type", length = 32)
    @Comment("来源单据类型")
    private String sourceBusinessType;

    @Column(name = "source_business_type_name", length = 64)
    @Comment("来源单据类型名称")
    private String sourceBusinessTypeName;

    @Comment("会员扩展信息")
    @Column(name = "customer_expand_id", length = 32)
    private String customerExpand;

    @Transient
    private Map customer;

    public Map getCustomer() {
        if (customerExpand == null) return null;
        Object customerExpand = SpringManager.getBean(DomainService.class).invoke("fn.customerExpand.findOne", MapUtil.mapper(
                "id", this.customerExpand
        ));
        if(ReflectUtil.getFieldValue(customerExpand, "mobile") == null) return null;
        return MapUtil.mapper(
                "realname", ReflectUtil.getFieldValue(customerExpand, "realName"),
                "vendorCode", ReflectUtil.getFieldValue(customerExpand, "vendorCode"),
                "mobile", ReflectUtil.getFieldValue(customerExpand, "mobile")
        );
    }

    @Transient
    private Map customerCar;

    public Map getCustomerCar() {
        if (customerExpand == null) return null;

        Object customerExpand = SpringManager.getBean(DomainService.class).invoke("fn.customerExpand.findOne", MapUtil.mapper(
                "id", this.customerExpand
        ));
        if(ReflectUtil.getFieldValue(customerExpand, "carLicense") == null) return null;
        return MapUtil.mapper(
                "carLicense", ReflectUtil.getFieldValue(customerExpand, "carLicense"),
                "vendorCode", ReflectUtil.getFieldValue(customerExpand, "vendorCode"),
                "mobile", ReflectUtil.getFieldValue(customerExpand, "mobile"),
                "customer", this.getCustomer()
        );
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "payer_id", referencedColumnName = "id")
    @Comment("交款人")
    private PartyRole payer;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "profit_center_id", referencedColumnName = "id")
    @Comment("利润中心")
    private DutyCenter profitCenterId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id")
    @Comment("部门编码")
    private Dept dept; //部门

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    @Comment("公司")
    private PartyRole company;

    @States(name = "状态", values = {
            @State(id = "sent", name = "申请"),
            @State(id = "approve", name = "已审核"),
            @State(id="done",name="完成")})
    @Column(name = "state")
    @Comment("状态(create:创建,approve:审核,done:完成)")
    private String state;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveUID;

    @Column(name = "approve_date")
    @Comment("审核日期")
    private Date approveDate;

    @Name
    @Column(name = "remark", length = 200)
    @Comment("备注")
    private String remark;

    @Column(name = "calculate_flag", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    @Comment("计费完成标记")
    private boolean calculateFlag = false;

    @OneToMany(mappedBy = "moneyIncome", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<MoneyIncomeItem> moneyIncomeItems = new ArrayList<>();

    @Column(name = "income_appId")
    @Comment("app单据ID")
    private String incomeAppId;

    public List<MoneyIncomeItem> getMoneyIncomeItems(){
        for (MoneyIncomeItem item : moneyIncomeItems) {
            item.setMoneyIncome(this);
        }
        return moneyIncomeItems;
    }

    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if(this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }


    @Transient
    private String realname;

    @Transient
    public String getRealname() {
        if (customerExpand == null) return null;
        Object customerExpand = SpringManager.getBean(DomainService.class).invoke("fn.customerExpand.findOne", MapUtil.mapper(
                "id", this.customerExpand
        ));
        if(ReflectUtil.getFieldValue(customerExpand, "mobile") == null) return null;
        return ReflectUtil.getFieldValue(customerExpand, "realName");

    }

    /**
     * 平台公司
     **/
    @Transient
    private PartyRole platformCompany;


    public PartyRole getPlatformCompany() {
        if (platformCompany != null) return platformCompany;
        String topic = "event:fn.contract.findFirstValidFnContractCompanyByPartnerId";
        String platformCompanyId = (String) EventUtil.sendSynEvent(this, topic, MapUtil.mapper("partnerId", getCompany().getId())).stream().findFirst().get();
        if (!StringUtils.isEmpty(platformCompanyId)) {
            platformCompany = (PartyRole) JpaUtil.getImplementation(SpringManager.getBean(PartyRoleService.class).findOne(platformCompanyId, "Company"));
            platformCompany = MapUtil.getO(MapUtil.mapped(platformCompany), PartyRole.class);
        }
        return  platformCompany;
    }
}
